using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class VNMenuManager : MonoBehaviour
{
    public static VNMenuManager instance;



    private MenuPage activePage = null;
    private bool isOpen = false;

    [SerializeField] private CanvasGroup rootCG;
    [SerializeField] private MenuPage[] pages;

    
    private UIConfirmationMenu uiChoiceMenu => UIConfirmationMenu.instance;

    private CanvasGroupController rootCGController;

    private void Awake()
    {
        instance = this;
    }


    // Start is called before the first frame update
    void Start()
    {
        rootCGController = new CanvasGroupController(this,rootCG);
    }

    private MenuPage GetPage(MenuPage.PageType pageType)
    {
        return pages.FirstOrDefault(page => page.pageType == pageType);
    }

    public void OpenSavePage()
    {
        var page = GetPage(MenuPage.PageType.SaveAndLoad);
        var slm = page.anim.GetComponentInParent<SaveAndLoadMenu>();
        slm.menuFunction = SaveAndLoadMenu.MenuFunction.save;
        OpenPage(page);
    }

    public void OpenLoadPage()
    {
        var page = GetPage(MenuPage.PageType.SaveAndLoad);
        var slm = page.anim.GetComponentInParent<SaveAndLoadMenu>();
        slm.menuFunction = SaveAndLoadMenu.MenuFunction.load;
        OpenPage(page);

    }

    public void OpenConfigPage()
    {
        var page = GetPage(MenuPage.PageType.Config);
        OpenPage(page);

    }

    public void OpenHelpPage()
    {
        var page = GetPage(MenuPage.PageType.Help);
        OpenPage(page);

    }

    private void OpenPage(MenuPage page)
    {
        if (page == null)
            return;

        if (activePage != null && activePage != page)
        {
            activePage.Close();
        }

        page.Open();
        activePage = page;
        if (!isOpen)
            OpenRoot();

    }

    public void OpenRoot()
    {
        rootCGController.Show();
        rootCGController.SetInteractableState(true);
        isOpen = true;
    }

    public void CloseRoot()
    {
        rootCGController.Hide();
        rootCGController.SetInteractableState(false);

        isOpen = false;
    }

    public void OpenHomePage()
    {
        VN_Configuration.activeConfig.Save();
        UnityEngine.SceneManagement.SceneManager.LoadScene(MainMenuManager.MAIN_MENU_SCENE);
    }

    

    public void OnQuitClick()
    {
        uiChoiceMenu.Show(
            "Quit to Desktop?",
            new UIConfirmationMenu.ConfirmationButton("Yes", () => Application.Quit()),
            new UIConfirmationMenu.ConfirmationButton("No",null)
            );
    }

}
